import { Controller } from "egg";
import jwt from 'jsonwebtoken'

const AiTokenRdKey = 'ai_token_get_user_new_1'

export default class AiController extends Controller {

  async getToken() {


    let cacheToken = await this.ctx.service.cache.get(AiTokenRdKey)
    if (!cacheToken) {
      const [id, secret] = this.config.aminer.key.split('.')
      const currentStp = Date.now()

      const payload = {
        api_key: id,
        exp: currentStp + 24 * 60 * 60 * 1000,
        timestamp: currentStp
      }
      cacheToken = jwt.sign(payload, secret, {
        algorithm: 'HS256',
        header: {
          "alg": "HS256", "sign_type": "SIGN"
        }
      })

      // token 24 小时
      this.service.cache.set(AiTokenRdKey, cacheToken, 60 * 60 * 24)
    } this.ctx.success({
      data: cacheToken
    })
  }

  async drawImage() {
    const { body, query } = this.ctx.validateReq('api.ai.draw')

    if (query.platform === 'baidu' && query.type === 'basic') {

      const data = await this.service.aiDraw.drawImgBasic(body.option)
      this.ctx.success({
        data
      })
    }
  }

  async queryImage() {
    const { query } = this.ctx.validateReq('api.ai.query')
    if (query.platform === 'baidu' && query.type === 'basic') {

      const data = await this.service.aiDraw.queryTaskBisic(query.taskId)
      this.ctx.success({
        data
      })
    }
  }

  getKetParam() {
    this.ctx.success({
      data: this.service.aiDraw.createChuangKetSign()
    })
  }

  async createVideos(){

    const { body } = this.ctx.request
    if(body){
      const res = await this.service.aiVideo.createVideos(body)
      if(res){
        this.ctx.success({
          data: res
        })
      }
    }
  }

  async getVideoResult(){
    const { query } = this.ctx.request
    if(query){
      const res = await this.service.aiVideo.queryResult(query.taskId)
      if(res){
        this.ctx.success({
          data: res
        })
      }
    }
  }
}